package com.shop.shop.Interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shop.shop.utile.JWTUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.HashMap;

public class JWTIntrtcptore implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        HashMap<String, Object> map = new HashMap<>();
        try {
            JWTUtils.verify(token);
                 return true;
                 }
        catch (TokenExpiredException e) {
            e.printStackTrace();
            map.put("msg","令牌过期异常");
        }
        catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            map.put("msg","算法不匹配异常");
        }
        catch (Exception e) {
            e.printStackTrace();
            map.put("msg","token无效");
        }
        Object asString = new ObjectMapper().writeValueAsString(map);
         response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(asString);
        return false;
    }
}
